package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/juju/ratelimit"
	"gorm.io/gorm"
	"mygo/app/models"
	"strconv"
	"time"
)

//基本的中间件

type BaseMiddleware struct {
	db *gorm.DB
}

var Base = BaseMiddleware{}
var limiter = ratelimit.NewBucketWithQuantum(time.Second, 10, 10) //capacity, quantum分别表示桶的容量和每次token补充量

// Limit 限流中间件
func (b *BaseMiddleware) Limit() gin.HandlerFunc {
	return func(c *gin.Context) {
		//limiter.TakeAvailable(1)表示取1个令牌，如果取不到则返回0
		if limiter.TakeAvailable(1) < 1 {
			c.JSON(401, gin.H{
				"code": 401,
				"msg":  "请求太频繁",
			})
			c.Abort()
			return
		}
		c.Next() //执行后续的处理函数
	}
}

// Logger 日志中间件
func (b *BaseMiddleware) Logger() gin.HandlerFunc {
	b.db = models.Db
	return func(c *gin.Context) {
		t := time.Now()
		//获取请求体
		c.Next()
		go func() {
			idC, _ := c.Cookie("userId")
			var user models.User
			b.db.First(&user, idC)
			//获取用户信息
			costTime := time.Since(t)
			//	存到数据库
			var log = models.Log{
				UserName:   user.Username,
				Time:       time.Now().Format("2006-01-02 15:04:05"),
				StatusCode: c.Writer.Status(),
				Method:     c.Request.Method,
				Path:       c.Request.URL.Path,
				Ip:         c.ClientIP(),
				Latency:    strconv.FormatInt(int64(costTime), 10),
			}
			b.db.Create(&log)
		}()
	}
}
